package com.yangtao.springbootfreemarker.web.controller.sys;

import cn.hutool.core.util.IdUtil;
import com.yangtao.core.utils.ConvertUtil;
import com.yangtao.core.utils.FileUtil;
import com.yangtao.core.web.ResultMsg;
import com.yangtao.springbootfreemarker.domain.sys.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class PdfController {

	@Autowired
	private SysUserDao sysUserDao;

	/**
	 * 登录
	 */
	/*@ResponseBody
	@RequestMapping(value = "/pub/pdf/convert", method = RequestMethod.POST)
	public void convert() throws IOException {
		try {
			String docuServer = "F:/images/images.war/ucamisweb/Images";
			List<Map<String, Object>> spList = sysUserDao.getSingProjectList();
			Map<String, String> fileMap;
			for(Map<String, Object> sp : spList) {
				System.err.println("--------------------------------------begin-------------------");
				String spOldId = sp.get("old_id").toString();
				System.out.println("开始转换单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));

				List<Map<String, Object>> rList = sysUserDao.getRecordList(MapUtil.getStr(sp, "id"));
				// 获取工程下的所有文件
				for(Map<String, Object> r : rList) {
					String fileUrl = (String) r.get("fileUrl");
					fileUrl = StringUtil.subBefore(fileUrl,".", false);
					String name = (String) r.get("name");
					String id = (String) r.get("id");
					String oldId = MapUtil.getStr(r, "old_id");
					if(StringUtil.isNotEmpty(fileUrl)) { // 已经存在路径
						String path = FileUtil.appendPath(docuServer, fileUrl); // 获取图片路径
						String oldPath = "/" + spOldId + "/" + oldId + "/" + oldId;
						if(StringUtil.equals(fileUrl, oldPath)) {
							System.out.println("文件名称【"+ name +"】,ID【"+ id +"】当前路径相同，不修改" );
							continue;
						}
						if(FileUtil.exist(path)) { // 文件已经存在
							// 获取当前文件夹下面的图片数量
							int dbPathCount = getFileCount(new File(path));
							if(dbPathCount == 0) { // 当前目录没有图片
								// TODO
								// 获取以前文件路径
								String oldAblPath = FileUtil.appendPath(docuServer, oldPath);
								if(StringUtil.isNotEmpty(oldAblPath)) { // 该路径存在
									// 直接修改当前文件路径为老的路径
									sysUserDao.updateRecordFileUrl(id, oldPath + ".pdf");
								}
							}
							// 获取组装数据
							System.err.println("--------------------------------------end-------------------");
							continue;
						}
					}
				}
				System.err.println("转换成功单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				System.err.println("--------------------------------------end-------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

	/**
	 * 转换file_url 为空的
	 */
	/*@ResponseBody
	@RequestMapping(value = "/pub/pdf/convertFileUrl", method = RequestMethod.POST)
	public void convertFileUrl() throws IOException {
		try {
			List<Map<String, Object>> spList = sysUserDao.getSingProjectList();
			Map<String, String> fileMap;
			for(Map<String, Object> sp : spList) {
				System.err.println("--------------------------------------begin-------------------");
				String spOldId = sp.get("old_id").toString();
				System.out.println("开始转换单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));

				List<Map<String, Object>> rList = sysUserDao.getRecordList(MapUtil.getStr(sp, "id"));
				// 获取工程下的所有文件
				for(Map<String, Object> r : rList) {
					String fileUrl = (String) r.get("fileUrl");
					String name = (String) r.get("name");
					String id = (String) r.get("id");
					String oldId = MapUtil.getStr(r, "old_id");
					if(StringUtil.isEmpty(fileUrl)) { // 已经存在路径
						String oldPath = "/" + spOldId + "/" + oldId;
						sysUserDao.updateRecordFileUrl(id, oldPath + ".pdf");
						System.err.println("修改fileUrl：" + name + ";oldId:" + oldId);
					}
				}
				System.err.println("转换成功单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				System.err.println("--------------------------------------end-------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

	/**
	 * 转换file_url 为空的
	 *
	 */
	/*@ResponseBody
	@RequestMapping(value = "/pub/pdf/convertInsertAi", method = RequestMethod.POST)
	public void convertAi() throws IOException {
		String pdfPath = "F:/images/images.war/ucamisweb";
		try {
			// 查询所有的单位工程
			List<Map<String, Object>> spList = sysUserDao.getAllSingProjectList();
			Map<String, String> fileMap;
			for(Map<String, Object> sp : spList) {
				System.err.println("--------------------------------------begin-------------------");
				String spId = sp.get("id").toString();
				String spOldId = MapUtil.getStr(sp,"old_id");
				System.out.println("开始转换单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				List<Map<String, Object>> rList = sysUserDao.getRecordNoAIList(spId);
				// 获取工程下的所有文件
				for(Map<String, Object> r : rList) {
					String fileUrl = (String) r.get("fileUrl");
					String path = FileUtil.appendPath(pdfPath, fileUrl);
					File file = new File(path);
					String name = (String) r.get("name");
					String id = (String) r.get("id");
					if(FileUtil.exist(file)) { // 文件存在
						sysUserDao.insertAccessoriesInfo(id, name + ".pdf", file.length(), fileUrl, id);
						System.out.println("添加数据：" + name + ".pdf," + "文件路径:" + path);
					} else {
						// 获取切片ID
						String sliceId = MapUtil.getStr(r,"sliceId");
						String oldId = MapUtil.getStr(r,"oldId");
						if(StringUtil.isNotEmpty(sliceId) && StringUtil.isNotEmpty(oldId)) {
							String oldFileUrl = "/" + sliceId + "/source/" + oldId + "/" + oldId + ".pdf";
							String oldAbsolutePath = FileUtil.appendPath(pdfPath, oldFileUrl);
							File oldFile = new File(oldAbsolutePath);
							if(oldFile.exists()) {
								sysUserDao.insertAccessoriesInfo(id, name + ".pdf", oldFile.length(), oldFileUrl, id);
								System.out.println("添加数据：" + name + ".pdf," + "文件路径:" + path);
							}
						}
					}
				}
				System.err.println("转换成功单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				System.err.println("--------------------------------------end-------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static int getFileCount(File file) {
		int i = 0;
		File[] files = file.listFiles();
		for(File fileTemp : files) {
			if(fileTemp.isDirectory()) {
				continue;
			} else {
				i ++;
			}
		}
		return i;
	}*/

	/**
	 * 转换file_url 为空的
	 *
	 */
	/*@ResponseBody
	@RequestMapping(value = "/pub/pdf/convertNoFileUrl", method = RequestMethod.POST)
	public void convertNoFileUrl() throws IOException {
		String pdfPath = "F:/images/images.war/ucamisweb";
		try {
			// 查询所有的单位工程
			List<Map<String, Object>> spList = sysUserDao.getAllSingProjectList();
			Map<String, String> fileMap;
			for(Map<String, Object> sp : spList) {
				System.err.println("--------------------------------------begin-------------------");
				String spId = sp.get("id").toString();
				System.out.println("开始转换单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				List<Map<String, Object>> rList = sysUserDao.getRecordYesAIList(spId);
				// 获取工程下的所有文件
				for(Map<String, Object> r : rList) {
					String accFileUrl = MapUtil.getStr(r, "accFileUrl");
					String path = FileUtil.appendPath(pdfPath, accFileUrl);
					String name = (String) r.get("name");
					String id = (String) r.get("id");
					System.err.println("修改文件name：" + name + ";id:"+ id +"; 路径：" + accFileUrl);
					sysUserDao.updateRecordFileUrl(id, accFileUrl);
				}
				System.err.println("转换成功单位工程：" + sp.get("name") + ";oldId:" + sp.get("old_id"));
				System.err.println("--------------------------------------end-------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/

	@ResponseBody
	@RequestMapping(value = "/pub/pdf/convertErrorPdf")
	public ResultMsg convertErrorPdf() {
		String path = "G:/images/images.war/ucamisweb";
		String sql = "select t.id as id, t.old_id as oldId, t.`name` from single_project t where t.old_id is not null";
		List<Map<String, Object>> spList = sysUserDao.nQueryListMap(sql);
		System.out.println("=============================================转换开始=============================================");
		for (Map<String, Object> spMap : spList) {
			String name = ConvertUtil.toStr(spMap.get("name"));
			String spId = ConvertUtil.toStr(spMap.get("id"));
			Integer oldId = ConvertUtil.toInt("oldId");
			System.out.println(String.format("单位工程开始转换：【%s】开始转换", name));
			sql = "select t.id as id, t.old_id as oldId, t.`name`  from record t where t.old_id is not null and t.single_project = ?";
			List<Map<String, Object>> recordList = sysUserDao.nQueryListMap(sql, spId);
			for(Map<String, Object> recordMap : recordList) {
				String recordId = ConvertUtil.toStr(recordMap.get("id"));
				// 获取电子文件
				sql = "select t.aii05c as relPath, t.aii01c as id from accessories_info t where t.aii10c = ?";
				List<Map<String, Object>> aiList = sysUserDao.nQueryListMap(sql, recordId);
				for(Map<String, Object> aiMap : aiList) {
					String relPath = ConvertUtil.toStr(aiMap.get("relPath"));
					String absolutePath = FileUtil.appendPath(path, relPath);
					File file = new File(absolutePath);
					if(file.exists()) {
						Long fileSize = file.length();
						if(fileSize < 1024 * 10) {
							String parentFile = FileUtil.getParent(absolutePath, 1);
							String backupPath = FileUtil.appendPath(parentFile, "backup_" + file.getName());
							if(FileUtil.exist(backupPath)) {
								FileUtil.copy(new File(backupPath), file, true);
								System.out.println(String.format("复制文件【%s】", ConvertUtil.toStr(recordMap.get("name"))));
							}
						}
					}
				}

			}
			System.out.println(String.format("单位工程结束转换：【%s】开始转换", name));
		}
		System.out.println("=============================================转换结束=============================================");
		return ResultMsg.buildSuccessMsg();
	}

	@ResponseBody
	@RequestMapping(value = "/pub/pdf/copyBzPdf")
	public ResultMsg copyBzPdf() {
		List<String> rootList = new ArrayList<>();
		rootList.add("E:\\fileSystem");
		String sql = "select id, name, number, old_id as oldId from record t where t.single_project is null";
		String savePath = "E:\\fileSystem";
		// 获取文件的总数量
		List<Map<String, Object>> recordList = sysUserDao.nQueryListMap(sql);
		for(Map<String, Object> recordMap : recordList) {
			String recordId = ConvertUtil.toStr(recordMap.get("id"));
			String recordName = ConvertUtil.toStr(recordMap.get("name"));
			String recordNumber = ConvertUtil.toStr(recordMap.get("number"));
			String oldId = ConvertUtil.toStr(recordMap.get("oldId"));
			sql = "select t.aii05c as relPath, t.aii01c as id from accessories_info t where t.aii10c = ?";
			List<Map<String, Object>> aiList = sysUserDao.nQueryListMap(sql, recordId);
			if(aiList != null && aiList.size() > 0) {
				for(Map<String, Object> aiMap : aiList) {
					// 处理已经关联的数据
					String relPath = ConvertUtil.toStr(aiMap.get("relPath"));

					File file = getFile(rootList, relPath);
					if(file != null && file.exists()) {
						break;
					} else {
						// 判断备份文件下是否有路径
						File backUpfile = getBackUpFile(recordNumber);
						if(backUpfile != null && backUpfile.exists()) {
							// 复制
							FileUtil.copy(backUpfile, new File(FileUtil.appendPath(savePath, relPath)), true);
							System.out.println(String.format("复制：路径存在：名称【%s】，路径【%s】", recordName, relPath));
						} else {
							System.err.println(String.format("路径存在，电子文件未找到：名称【%s】，路径【%s】", recordName, relPath));
						}
					}
				}
			} else {
				// 处理未关联的数据
				File backUpfile = getBackUpFile(recordNumber);
				if(backUpfile != null && backUpfile.exists()) {
					String fileName = recordNumber + ".pdf";
					String relPath = FileUtil.appendPath("\\oldfiles\\", fileName);
					// 复制
					FileUtil.copy(backUpfile, new File(FileUtil.appendPath(savePath, relPath)), true);
					// 修改ai
					String insertSql = "insert into accessories_info values (?, ?, 1, ?, ?, 0, '2020-06-12 14:30:00', 'admin', 'Record', ?, 0, 1, 'admin', '256600', 0, null, null)";
					sysUserDao.nUpdate(insertSql, IdUtil.randomUUID(), fileName, backUpfile.length(), relPath, recordId);
					System.out.println(String.format("新增：路径不存在，备份存在：名称【%s】，路径【%s】", recordName, relPath));
				}
			}

		}
		return ResultMsg.buildSuccessMsg();
	}

	/**
	 * 获取电子文件备份路径
	 * @param recordNumber
	 */
	private File getBackUpFile(String recordNumber) {
		//String backUpPath = "H:\\旧资料(备份)";
		String backUpPath = "F:\\00000";
		String absolutePath = FileUtil.appendPath(backUpPath, recordNumber + ".pdf");
		return FileUtil.file(absolutePath);
	}

	/**
	 * 获取文件
	 * @param rootList
	 * @param relPath
	 * @return
	 */
	private File getFile(List<String> rootList, String relPath) {
		File file = null;
		for(String root : rootList) {
			String absolutePath = FileUtil.appendPath(root, relPath);
			file = FileUtil.file(absolutePath);
			if(file != null && file.exists()) { // 判断文件不为空，且文件存在
				break;
			}
			file = null;
		}
		return file;
	}

}
